package com.ruicar.afs.cloud.afscase.common.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.ruicar.afs.cloud.afscase.common.config.PriceUrlConfig;
import com.ruicar.afs.cloud.afscase.common.service.AggregateService;
import com.ruicar.afs.cloud.afscase.common.utils.DicUtils;
import com.ruicar.afs.cloud.afscase.paramconfmanagement.service.CaseConfParamService;
import com.ruicar.afs.cloud.aggregate.aggregateport.AggregateApiFeign;
import com.ruicar.afs.cloud.aggregate.dto.CertNoDto;
import com.ruicar.afs.cloud.aggregate.dto.ValuationDto;
import com.ruicar.afs.cloud.aggregate.dto.VinInfoDto;
import com.ruicar.afs.cloud.common.modules.afscorebusiness.enums.ParamLogoEnum;
import com.ruicar.afs.cloud.components.datadicsync.DicHelper;
import com.ruicar.afs.cloud.components.datadicsync.dto.DicDataDto;
import com.ruicar.afs.cloud.message.sendmessage.config.MessageConfig;
import com.ruicar.afs.cloud.vehicle.dto.CarInfoDto;
import com.ruicar.afs.cloud.vehicle.feign.VehicleApiFeign;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


@AllArgsConstructor
@Service
@Slf4j
public class AggregateServiceImpl implements AggregateService {
    private AggregateApiFeign aggregateApiFeign;
    private VehicleApiFeign vehicleApiFeign;
    private CaseConfParamService paramService;
    private final PriceUrlConfig priceUrlConfig;

    /**
     * @description: 二手车历史存量vin查询
     * @author jiaqi.guo
     * @created 2020/7/15 16:35
     * @version 1.0
     */
    public List<VinInfoDto> getUsedcarHis(String vin,String applyNo) {
        //判断开关
        boolean bool=paramService.getIsOpen(ParamLogoEnum.ISOPEN.getCode());
        if(!bool){
            log.info("接口开关关闭");
            return null;
        }
        List<VinInfoDto> vinList = new ArrayList();
        try {
            JSONObject json = aggregateApiFeign.getUsedCar(vin);
            log.info("历史存量vin查询返回JSON:-------------------------------" + json);
            if (1 == json.getInteger("success")) {
                JSONArray jsonArray = json.getJSONArray("data");
                if (jsonArray.size() > 0) {
                    for (int i = 0; i < jsonArray.size(); i++) {
                        VinInfoDto vinInfo = JSONObject.parseObject(JSONObject.toJSONString(jsonArray.get(i)), VinInfoDto.class);
                        if(ObjectUtils.isNotEmpty(vinInfo)&&!vinInfo.getApplicationNo().equals(applyNo)){
                            vinList.add(vinInfo);
                        }
                    }
                }
            } else {
                log.info("请求失败:" + json.getString("message"));
            }
        } catch (Exception e) {
            log.info("二手车历史存量vin异常：" + e.getMessage());
        }
        return vinList;
    }

    /**
     * @description: 历史贷款金额
     * @author jiaqi.guo
     * @created 2020/7/16 11:33
     * @version 1.0
     */
    public BigDecimal getLoanhistory(CertNoDto certNoDto) {
        //判断开关
        boolean bool=paramService.getIsOpen(ParamLogoEnum.ISOPEN.getCode());
        if(!bool){
            log.info("接口开关关闭");
            return null;
        }
        BigDecimal loanAmount = BigDecimal.ZERO;
        try {
            JSONObject json = aggregateApiFeign.getLoanhistory(certNoDto.getBorrowerCertno(), certNoDto.getCoborrowerCertno());
            log.info("历史贷款额度返回JSON:-------------------------------" + json);
            if (1 == json.getInteger("success")) {
                JSONArray jsonArray = json.getJSONArray("data");
                if (jsonArray.size() > 0) {
                    for (int i = 0; i < jsonArray.size(); i++) {
                        CertNoDto cerNo = JSONObject.parseObject(JSONObject.toJSONString(jsonArray.get(i)), CertNoDto.class);
                        loanAmount = loanAmount.add(cerNo.getLoanAmount());
                    }
                }
            } else {
                log.info("请求失败:" + json.getString("message"));
            }
        } catch (Exception e) {
            log.info("历史贷款额度异常：" + e.getMessage());

        }
        return loanAmount;
    }

    /**
     * @description: 车辆查询
     * @author jiaqi.guo
     * @created 2020/7/16 14:18
     * @version 1.0
     */
    public String getPriceUrl(CarInfoDto carInfoDto) {
        //判断开关
        boolean bool=paramService.getIsOpen(ParamLogoEnum.ISOPEN.getCode());
        if(!bool){
            log.info("接口开关关闭");
            return null;
        }
        String priceUrl = "";
        try {
            JSONObject json = vehicleApiFeign.cjcxurl(carInfoDto);
            log.info("车架查询URL-------------------------------" + json);
            if (0 == json.getInteger("code")) {
                log.info("请求成功:" + json);
                JSONObject jsonObject = json.getJSONObject("data");
                if (ObjectUtils.isNotEmpty(jsonObject)) {
                    priceUrl = jsonObject.getString("url");
                    if(StringUtils.isNotBlank(priceUrl)){
                        priceUrl=priceUrl.replace(priceUrlConfig.getBackUrl()
                        ,priceUrlConfig.getReverseUrl());
                    }
                    log.info("URL地址:" + priceUrl);
                }
            } else {
                log.info("请求失败:" + json.getString("msg"));
            }
        } catch (Exception e) {
            log.info("车架查询异常：" + e.getMessage());
        }
        return priceUrl;
    }

    /**
     * @description: 估值报告比对数据
     * @author jiaqi.guo
     * @created 2020/7/16 17:12
     * @version 1.0
     */
    public ValuationDto getValuationReport(CarInfoDto carInfoDto) {
        //判断开关
        boolean bool=paramService.getIsOpen(ParamLogoEnum.ISOPEN.getCode());
        if(!bool){
            log.info("接口开关关闭");
            return null;
        }
        ValuationDto valuationDto = new ValuationDto();
        try {
            JSONObject json = vehicleApiFeign.pgbgjson(carInfoDto);
            log.info("估值报告比对数据返回JSON-------------------------------" + json);
            if (0 == json.getInteger("code")) {
                JSONArray jsonArray = json.getJSONArray("data");
                if (CollectionUtils.isNotEmpty(jsonArray)) {
                    JSONObject jsonObject = jsonArray.getJSONObject(0);
                    JSONObject jsonInfo = jsonObject.getJSONObject("content");
                    if (ObjectUtils.isNotEmpty(jsonInfo)) {
                        valuationDto.setVin(jsonInfo.getString("vin"));
                        //发动机号
                        valuationDto.setEngineNo(jsonInfo.getString("EngineNo"));
                        //过户次数
                        valuationDto.setCarTransferNumber(jsonInfo.getString("CarTransferNumber"));
                        //首次登记日期
                        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-mm-dd hh:mm:ss");
                        valuationDto.setRegDate(dateFormat.format(jsonInfo.getDate("RegDate")));
                        //事故车字典
                        Map<String, List<DicDataDto>> dicMap = DicHelper.getDicMaps("accidentType");
                        if (StringUtils.isNotBlank(jsonInfo.getString("accidenttype"))) {
                            String accidenttype = "";
                            String[] str = jsonInfo.getString("accidenttype").split(",");
                            if (str.length == 1) {
                                accidenttype = DicUtils.translate(jsonInfo.getString("accidenttype"), dicMap);
                            } else {
                                for (int i = 0; i < str.length; i++) {
                                    valuationDto.setAccidenttype(DicUtils.translate(jsonInfo.getString("accidenttype"), dicMap));
                                    accidenttype += DicUtils.translate(jsonInfo.getString("accidenttype"), dicMap) + " ";
                                }
                            }
                            //事故类型
                            valuationDto.setAccidenttype(accidenttype);
                            log.info("事故类型:" + accidenttype);
                        }
                    }
                    //车牌号
                    valuationDto.setGBNo(jsonInfo.getString("GBNo"));
                    //使用性质
                    valuationDto.setCarUsetype(jsonInfo.getString("car_Usetype"));
                    //所有人
                    valuationDto.setOwnerName(jsonInfo.getString("OwnerName"));

                }
            } else {
                log.info("请求失败:" + json.getString("msg"));
            }

        } catch (Exception e) {
            log.info("估值报告比对数据异常：" + e.getMessage());
        }
        return valuationDto;
    }

}
